import { Controller } from 'egg';
import { Result } from '../util/result';
import MsgEnum from '../util/msgEnum';

export default class ProductController extends Controller {
  async getList() {
    const { ctx, app } = this;

    const errors = app.validator.validate(
      {
        page: { require, type: 'int', convertType: 'int' },
      },
      ctx.request.body
    );
    if (errors) {
      ctx.status = 400;
      ctx.body = new Result(errors, MsgEnum.PARAMETER_VERIFICATION_ERROR);
    } else {
      const { page } = ctx.request.body;
      const result = await this.ctx.service.talentType.getList(page);
      if (result.mainData) {
        ctx.body = result;
      } else {
        ctx.status = 406;
        ctx.body = result;
      }
    }
  }

  public async del() {
    const { ctx, app } = this;

    const errors = app.validator.validate(
      {
        uuid: { require, type: 'string' },
      },
      ctx.request.body
    );
    if (errors) {
      ctx.status = 400;
      ctx.body = new Result(errors, MsgEnum.PARAMETER_VERIFICATION_ERROR);
    } else {
      const { uuid } = ctx.request.body;
      const result = await this.ctx.service.talentType.del(uuid);
      if (result.mainData) {
        ctx.body = result;
      } else {
        ctx.status = 406;
        ctx.body = result;
      }
    }
  }

  public async insert() {
    const { ctx, app } = this;

    const errors = app.validator.validate(
      {
        typeName: { require, type: 'string' },
        typeDescription: { require, type: 'string' },
      },
      ctx.request.body
    );
    if (errors) {
      ctx.status = 400;
      ctx.body = new Result(errors, MsgEnum.PARAMETER_VERIFICATION_ERROR);
    } else {
      const { typeName, typeDescription } = ctx.request.body;
      const result = await this.ctx.service.talentType.insert(
        typeName,
        typeDescription
      );
      if (result.mainData) {
        ctx.body = result;
      } else {
        ctx.status = 406;
        ctx.body = result;
      }
    }
  }

  public async haveTalent() {
    const { ctx, app } = this;

    const errors = app.validator.validate(
      {
        uuid: { require, type: 'string' },
      },
      ctx.request.body
    );
    if (errors) {
      ctx.status = 400;
      ctx.body = new Result(errors, MsgEnum.PARAMETER_VERIFICATION_ERROR);
    } else {
      const { uuid } = ctx.request.body;
      const talents = await this.ctx.model.Talent.findAll({
        where: { pk_type: uuid },
      });

      const result = talents.length !== 0;
      ctx.body = new Result(result);
    }
  }
}
